// packageC/video_goods/VideoList/VideoList.js
var app = getApp();
var colOneHeight = 0;
var colTwoHeight = 0;
const storeAlone = "plugin.store-alone-temp.frontend.videoShare.video.get-list";
// var width = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    videoList: [],
    showLoading: false,
    imgCount: 0,
    //more
    isLoadMore: true,
    page: 1,
    total_page: 0,
    bannerList: [],
    activitys1: [],
    activitys2: [],
    imagedata: {
      img_0: '../../../image/icon_index.png',
      img_1: '../../../image/icon_component.png',
      img_2: '../../../image/icon_commission.png',
      img_3: '../../../image/icon_cart.png',
      img_4: '../../../image/icon_I.png'
    },
    iPnoneBottomBol: false,
    videoMore: 'https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/video_more@2x.png',
    viderCancle: 'https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/video_cancle@2x.png',
    btnStatus: false,
    is_rotation: 0,

    is_show_cate: false,
    cateList: [{
      id: 0,
      name: "全部"
    }], //分类
    category_id: 0,
    swiperHeight: '',
    listData: [],
    taskID:'',
    taskDay:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getiPnoneBottom();
    if (options.cat_id !== undefined && options.cat_id !== null) {
      this.setData({
        category_id: Number(options.cat_id)
      });
    }
    if(options.taskID){
      this.setData({
        taskID:options.taskID
      })
    }
    if(options.taskDay){
      this.setData({
        taskDay:options.taskDay
      })
    }
    if (app.globalData.store_alone_temp == 1) {
      this.getData();
    } else {
      this.getData();
      this.getBanner();
      this.getBasicSet();
    }
  },
  imageLoad: function (e) { //获取图片真实宽度
    // var imgwidth = e.detail.width,
    //   imgheight = e.detail.height,
    //宽高比
    let ratio = e.detail.width / e.detail.height;
    console.log(e.detail.width, e.detail.height);
    //计算的高度值
    var viewHeight = 750 / ratio;
    if (viewHeight > this.data.swiperHeight) {
      this.setData({
        swiperHeight: viewHeight
      });
    }
    // var imgheight = viewHeight;
    // var imgheights = this.data.bannerList;
    // //把每一张图片的对应的高度记录到数组里
    // imgheights[e.target.id] = imgheight;
    // this.setData({
    //   imgheights: imgheights
    // });
  },
  bindchange: function (e) {
    // console.log(e.detail.current)
    this.setData({
      current: e.detail.current
    });
  },
  chooseSta() {
    this.setData({
      btnStatus: !this.data.btnStatus
    });
  },
  goluzhi() {
    wx.navigateTo({
      url: '/packageC/video_goods/releaseVideo/releaseVideo',
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  gojilu(e) {
    wx.navigateTo({
      url: '/packageC/video_goods/myVideo/myVideo',
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多数据');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getiPnoneBottom() {
    let that = this;
    try {
      var value = wx.getStorageSync('iPhoneBottom');
      if (value) {
        that.setData({
          iPnoneBottomBol: true
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  getBanner() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.set.getSlide");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            bannerList: res.data.slide,
            is_rotation: res.data.is_rotation
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  /**
   * 图片加载函数
   * 图片加载完成后，根据图片的高度，依次往第一列和第二列中推入数据
   */
  onImageLoad(options) {
    let activitys = this.data.videoList; // 获取所有的数据资源
    this.data.listData.push(options)
    this.data.imgCount += 1;
    if (this.data.imgCount == this.data.videoList.length) {
      let activityObj = null;
      let imageWidth = 0; // 图片宽度
      let imageHeight = 0; // 图片高度
      let data = {}
      function sortId(a, b) {
        return parseInt(b.currentTarget.id) - parseInt(a.currentTarget.id);
      }
      this.data.listData.sort(sortId)
      this.data.listData.forEach((item, index) => {
        imageWidth = item.detail.width; // 图片宽度
        imageHeight = item.detail.height; // 图片高度
        let scle = (imageWidth / imageHeight);
        for (let i = 0; i < activitys.length; i++) {
          if (activitys[i].id == parseInt(item.currentTarget.id)) {
            activityObj = activitys[i];
            break;
          }
        }
        let activitys1 = this.data.activitys1;
        let activitys2 = this.data.activitys2;
        if (colOneHeight <= colTwoHeight) {
          colOneHeight += (176 / scle) + 60;
          activitys1.push(activityObj);
        } else {
          colTwoHeight += (176 / scle) + 60;
          activitys2.push(activityObj);
        }
        data = {
          activitys1: activitys1,
          activitys2: activitys2
        };
      })
      this.setData(data);
      this.data.listData = []
    }
  },

  changeCategory(e) {
    this.data.category_id = e.detail.name;
    this.data.imgCount = 0
    this.getData();
  },
  getData() {
    let that = this;
    this.data.page = 1;
    let urlStr = app.getNetAddresss(app.globalData.store_alone_temp == 1 ? storeAlone : "plugin.video-share.frontend.video.getList");
    app._postNetWork({
      url: urlStr,
      data: {
        page: 1,
        search: {
          category_id: this.data.category_id
        }
      },
      success: function (resdata) {
        that.setData({
          showLoading: true
        });
        try {
          let name = wx.getStorageSync('yz_basic_info');
          let shopName = name.home.mailInfo.name || '';
          wx.setNavigationBarTitle({
            title: shopName
          });
        } catch (err) {}
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            isLoadMore: true
          });
          that.data.total_page = res.data.list.last_page;
          if (!that.data.total_page) {
            that.data.total_page = 0;
          }
          that.setData({
            videoList: []
          });
          colOneHeight = 0;
          colTwoHeight = 0;
          that.setData({
            activitys1: [],
            activitys2: [],
            videoList: res.data.list.data
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getBasicSet() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.video.getBasicSet");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1 && res.data.set.is_show_cate == '1') {
          that.getCategory();
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  getCategory() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.video-share.frontend.video.getCategory");
    app._getNetWork({
      url: urlStr,
      data: {},
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            cateList: that.data.cateList.concat(res.data),
            is_show_cate: true
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  toVideo(e) {
    let item = e.currentTarget.dataset.item;
    let page = this.data.videoList.findIndex((value, index, arr) => {
      return value.id === item.id;
    });
    page = Math.ceil((page + 1) / 15);
    if(this.data.taskID){
      wx.navigateTo({
        url: '/packageC/video_goods/VideoDetail/VideoDetail?vid=' + item.id + '&page=' + page + '&category=' + (this.data.category_id > 0 ? true : false) +'&taskID='+this.data.taskID+'&taskDay='+this.data.taskDay+'&task_type=video'
      });
    }else{
      wx.navigateTo({
        url: '/packageC/video_goods/VideoDetail/VideoDetail?vid=' + item.id + '&page=' + page + '&category=' + (this.data.category_id > 0 ? true : false)
      });
    }
    
  },
  gotoUpload() {
    wx.navigateTo({
      url: '/packageC/video_goods/videoAgreement/videoAgreement'
    });
  },
  getMoreData() {
    const that = this;
    that.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      this.data.page = this.data.page + 1;
      let urlStr = app.getNetAddresss(app.globalData.store_alone_temp == 1 ? storeAlone : "plugin.video-share.frontend.video.getList");
      app._postNetWork({
        url: urlStr,
        data: {
          page: that.data.page,
          search: {
            category_id: this.data.category_id
          }
        },
        success: function (resdata) {
          var res = resdata.data;
          that.data.isLoadMore = true;
          if (res.result == 1) {
            let myData = res.data.list.data;
            that.setData({
              videoList: that.data.videoList.concat(myData) //数组拼接
            });
          } else {
            that.data.page = that.data.page - 1;
            that.data.isLoadMore = false;
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  goimgurl(e) {
    console.log(e);
    let url = e.currentTarget.dataset.url;
    console.log(url);
    try {
      wx.navigateTo({
        url: url
      });
    } catch (e) {
      wx.showToast({
        title: '链接设置错误',
        icon: 'none',
        duration: 2000
      });
      //TODO handle the exception
    }
  },
  goindex() {
    wx.reLaunch({
      url: '/packageG/index/index'
    });
  },
  gocategory() {
    wx.reLaunch({
      url: '/packageG/pages/category_v2/category_v2'
    });
  },
  gocart() {
    wx.reLaunch({
      url: '/packageG/pages/buy/cart_v2/cart_v2'
    });
  },
  gomember() {
    wx.reLaunch({
      url: '/packageG/member_v2/member_v2'
    });
  },
});